package org.jks.service;

import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;

public class EntityService<T> extends BaseDaoImpl<T> {
	public String MODEL_NAME = "";
	public Class<?> CLASS_NAME = null;
	
	public long count() {
		return count("select count(*) from " + MODEL_NAME);
	}

	public List<T> all() {
		return find("from " + MODEL_NAME);
	}

	public List<T> list(int page, int pagesize) {
		List<Object> param = null;
		return find("from " + MODEL_NAME, param, page,
				pagesize);
	}

	public Object delete(long id) {
		Object obj = null;
		Session session = this.openSession();
		try{
			obj = session.get(CLASS_NAME, id);
			session.delete(session.get(CLASS_NAME, id));
		}
		catch(Exception e){
		}
		session.flush();
		session.close();
		return obj;
	}

	public void delete(long[] ids) {
		Session session = this.openSession();
		StringBuilder strIds = new StringBuilder();
		strIds.append('(');
		int imax = ids.length - 1;
		for (int i = 0;; i++) {
			strIds.append(ids[i]);
			if (i == imax) {
				strIds.append(')');
				break;
			}
			strIds.append(", ");
		}
		String sql = "delete from "
				+ MODEL_NAME + " where id in " + strIds;
		System.out.println(sql);
		SQLQuery sqlQuery = session.createSQLQuery("delete from "
				+ MODEL_NAME + " where id in " + strIds);
		sqlQuery.executeUpdate();
		session.flush();
		session.close();
	}
	
	public void delete(String hql){
		Session session = this.openSession();
		SQLQuery sqlQuery = session.createSQLQuery(hql);
		sqlQuery.executeUpdate();
		session.flush();
		session.close();
	}

	@SuppressWarnings("unchecked")
	public T findById(long id) {
		return get((Class<T>) CLASS_NAME, id);
	}
	
	public T first(){
		return first("from " + MODEL_NAME);
	}
	
	public void remove(T o){
		Session session = this.openSession();
		session.delete(o);
		session.close();
	}
	
	public void removeAll(){
		Session session = this.openSession();
		session.beginTransaction();
		try{

			@SuppressWarnings("unchecked")
			List<T> entities = session.createQuery(" from " + MODEL_NAME).list();
			if(entities != null && entities.size() > 0){
				for(T entity : entities){
					session.delete(entity);
				}
			}
			session.getTransaction().commit();
		}
		catch(Exception e){
			session.getTransaction().rollback();
		}
		session.close();
	}

}
